package com.zzyl.framework.interceptor;

import cn.hutool.core.util.ObjectUtil;
import com.zzyl.common.utils.MemberThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 拦截C端访问
 *
 * @author: JBY
 * @since: 2025/08/20 15:55
 */
@Component
@Slf4j
public class MemberInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //如果访问的不是controller方法, 即静态资源, 则直接放行
        if(!(handler instanceof HandlerMethod)){
            return true;
        }

        try {
            //非空校验
            String token = tokenService.getToken(request);
            if (ObjectUtil.isNull(token)) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                return false;
            }
            //解析token
            Claims claims = tokenService.parseToken(token);
            //claims非空校验
            if (ObjectUtil.isNull(claims)) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                return false;
            }
            //从claims中获取ID
            Object id = claims.get("memberId");
            //id非空校验
            if (ObjectUtil.isNull(id)) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                return false;
            }
            //设置用户id
            MemberThreadLocal.setMemberId(Long.parseLong(id.toString()));
            log.info("用户id:{}", id);
            return true;
        } catch (Exception e) {
            log.error("用户信息获取失败:{}", e.getMessage());
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //避免内存泄漏
        MemberThreadLocal.remove();
    }
}
